<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ok_fish
 * Date: 18-1-20
 * Time: 下午2:23
 * To change this template use File | Settings | File Templates.
 */

//调用代码

require './OauthClient.php';
//Step1：获取Authorization Code
session_start();
$code = isset($_REQUEST["code"])?$_REQUEST["code"]:'';
if(empty($code))
{
    //state参数用于防止CSRF攻击，成功授权后回调时会原样带回
    $_SESSION['state'] = md5(uniqid(rand(), TRUE));
    $data['state'] =  $_SESSION['state'];
    $authorze_url = OauthClient::getAuthorizeUrl($data);
    header('Location:'.$authorze_url);
}


if($_REQUEST['state'] == $_SESSION['state'])
{
    //Step2：通过Authorization Code获取Access Token
    $data = array(
        'code'=>$code,
    );

    if(!empty($_SESSION['token']) && $_SESSION['token_expire_at']>time()){
        $token =  $_SESSION['token'];

    }else{
        $token =  OauthClient::getToken($data);

    }



    //Step3：使用Access Token来获取用户的OpenID
    if(!empty($token['access_token']))
    {

        $_SESSION['token'] = $token;
        $_SESSION['token_expire_at'] = time()+$token['expires_in'];
        $user_info =  OauthClient::getApiData($token);
        var_dump($user_info);
        // 通过$user_info['openid'] 去查用户表的记录
        /*
        查询数据库  uid openid 来源等等
        if(如果存在记录,已经绑定){
            //直接做登录处理
        }else{
            //跳转到绑定页面 输入用户名密码 完成绑定 更新数据库openid字段
        }
        */


    }else{
        exit('token error...');
    }
}else{
    exit("csrf...");
}